/**
 * 我的合同 - 底部操作按钮
 * 编辑中 撤回 审批驳回：编辑 提交 删除合同 返回
 * 审批中：撤回 返回
 * 审批通过：暂挂 已完成 授权 变更 取消 返回
 * 暂挂：取消暂挂 返回
 * 已取消 已完成：返回
 */
import React, { Component } from "react";
import { Affix, Button, message, Modal } from "antd";
import menuRoute from "routes/menuRoute";
import { messages } from "share/common";
import errorMessage from "share/errorMessage";
import Space from "components/space";
import contractService from "../contract.service";
import MentionBtn from "../../request/btns/mention-btn";
import AuthorizeBtn from "../authorize-btn";
import requestService from "../../request/request.service";
import Designate from "components/template/designate";

class ContractBottomBar extends Component {
  state = {
    loadingBtn: null,
    needRefresh: false,
    designateVisible: false,
  };

  setLoadingBtn = (loadingType = null) => {
    this.setState({ loadingBtn: loadingType });
  };

  handleSuccess = () => {
    message.success(messages("common.operate.success") /*操作成功*/);
    this.setState({ needRefresh: true });
    this.props.refreshContractInfo();
    this.props.refreshHistory();
  };

  changeContractStatus = (type) => {
    const typeMap = new Map([
      [
        "hold",
        {
          service: "holdContract",
          name: messages("finance-6.key5") /*暂挂*/,
        },
      ],
      [
        "unHold",
        {
          service: "unHoldContract",
          name: messages("finance-6.key3") /*审批通过*/,
        },
      ],
      [
        "finish",
        {
          service: "finishContract",
          name: messages("finance-6.key7") /*已完成*/,
        },
      ],
      [
        "cancel",
        {
          service: "cancelContract",
          name: messages("finance-6.key6") /*已取消*/,
        },
      ],
    ]);
    Modal.confirm({
      title: messages("finance-6.key136") /*合同状态变更*/,
      content: messages("finance-6.key137", { arg1: typeMap.get(type).name }) /*确定将合同变为{arg1}？*/,
      onOk: () => {
        this.setLoadingBtn(type);
        contractService[typeMap.get(type).service](this.props.contractInfo.id)
          .then(() => {
            this.handleSuccess();
          })
          .catch((e) => {
            errorMessage(e.response);
          })
          .finally(() => {
            this.setLoadingBtn();
          });
      },
    });
  };

  // 编辑
  handleEdit = () => {
    const { documentOid, contractTypeId, formOid } = this.props.contractInfo;
    this.context.router.push(
      menuRoute
        .getRouteItem("edit-contract")
        .url.replace(":entityOID", documentOid)
        .replace(":contractTypeId", contractTypeId)
        .replace(":formOID", formOid)
    );
  };

  regularCheck = () => {
    const { entityOID, contractInfo } = this.props;
    if (contractInfo.contractName) {
      this.setLoadingBtn("submit");
      contractService
        .submitContract(entityOID)
        .then(() => {
          message.success(messages("common.operate.success") /*操作成功*/);
          this.handleBack(true);
        })
        .catch((e) => {
          errorMessage(e.response);
        })
        .finally(() => {
          this.setLoadingBtn();
        });
    } else {
      message.error(messages("finance-6.key72") /*请添加合同信息*/);
    }
  };

  handleSubmit = async () => {
    try {
      const {
        contractInfo: { formOid, applicantOid },
        entityOID,
      } = this.props;
      let isDesignate = await requestService.getIsDesignate({
        formOID: formOid,
        applicantOID: applicantOid,
      });
      if (isDesignate.data && isDesignate.data.showDesignate) {
        this.setLoadingBtn("submit");
        requestService
          .getNodeList({
            entityOID,
            entityType: 6001,
          })
          .then((res) => {
            let nodeList = res.data.approvalDesignateNodeList || [];
            if (nodeList.length) {
              this.setState({
                designateVisible: true,
                nodeList,
              });
            } else {
              this.realSubmit();
            }
          })
          .catch((err) => {
            this.setLoadingBtn();
            errorMessage(err.response);
          });
      } else {
        this.realSubmit();
      }
    } catch (e) {
      message.error(e.response.data.message);
    }
  };

  handleCloseDesignate = (isSuccess) => {
    this.setState({
      designateVisible: false,
    });
    if (isSuccess) {
      this.realSubmit();
    } else {
      this.setLoadingBtn();
    }
  };

  //提交
  realSubmit = () => {
    const { enable, amount, contractId, handleOpenContractModal, handleBackData } = this.props;
    this.setLoadingBtn("submit");
    if (enable) {
      let params = {
        amount: amount,
        contractHeaderId: contractId,
      };
      contractService
        .postCheckResult(params)
        .then((res) => {
          this.setLoadingBtn();
          if (res.status === 200) {
            const data = res.data || {};
            const checkPass = data.checkPass;
            if (checkPass) {
              this.regularCheck();
            } else {
              handleOpenContractModal();
              handleBackData(data.checkResultList);
            }
          }
        })
        .catch((e) => {
          this.setLoadingBtn();
          message.error(`${messages("common.operate.filed") /*操作失败*/}，${e.response.data.message}`);
        });
    } else {
      this.setLoadingBtn();
      this.regularCheck();
    }
  };

  handleOk = () => {
    this.regularCheck();
  };

  // 删除合同
  handleDelete = () => {
    Modal.confirm({
      title: messages("finance-6.key75") /*删除合同*/,
      content: messages("finance-6.key138") /*确定删除该合同？*/,
      onOk: () => {
        this.setLoadingBtn("delete");
        contractService
          .deleteContract(this.props.entityOID)
          .then(() => {
            message.success(messages("common.delete.success", { arg1: "" }) /*{arg1} 删除成功*/);
            this.handleBack(true);
          })
          .catch((e) => {
            errorMessage(e.response);
          })
          .finally(() => {
            this.setLoadingBtn();
          });
      },
    });
  };

  // 撤回
  handleWithdraw = () => {
    const { formOid, documentOid, documentType, id } = this.props.contractInfo;
    // service recallWorkflowContract：走工作流
    // service recallContract：不走工作流，走审核
    const service = formOid ? "recallWorkflowContract" : "recallContract";
    const params = {
      entities: [
        {
          entityOID: documentOid,
          entityType: documentType,
        },
      ],
    };
    this.setLoadingBtn("withdraw");
    contractService[service](formOid ? params : id)
      .then(() => {
        this.handleSuccess();
      })
      .catch((e) => {
        errorMessage(e.response);
      })
      .finally(() => {
        this.setLoadingBtn();
      });
  };

  // 暂挂
  handleHold = () => {
    this.changeContractStatus("hold");
  };

  // 已完成
  handleFinish = () => {
    this.changeContractStatus("finish");
  };

  // 变更
  handleChange = () => {
    Modal.confirm({
      title: messages("finance-6.key139") /*确认变更合同吗？*/,
      content: messages(
        "finance-6.key140"
      ) /*若点击变更，系统将会把合同状态变更为编辑中，无法回撤，同时允许对合同进行变更，变更后需要重新走审批流进行审批*/,
      okText: messages("finance-6.key141") /*变更*/,
      onOk: () => {
        this.setLoadingBtn("change");
        contractService
          .changeContract(this.props.contractInfo.id)
          .then(() => {
            this.handleSuccess();
          })
          .catch((e) => {
            errorMessage(e.response);
          })
          .finally(() => {
            this.setLoadingBtn();
          });
      },
    });
  };

  // 取消
  handleCancel = () => {
    this.changeContractStatus("cancel");
  };

  // 取消暂挂
  handleUnHold = () => {
    this.changeContractStatus("unHold");
  };

  // 返回
  handleBack = (flag) => {
    const { needRefresh } = this.state;
    const { close } = this.props;
    close ? close(flag || needRefresh) : this.context.router.push(menuRoute.getRouteItem("my-contract").url);
  };

  filterButtons = (key) => {
    const {
      readOnly,
      entry,
      contractInfo: { status, contractChangeEnabled, isContractDocumentRelation },
    } = this.props;
    switch (key) {
      case "edit":
      case "submit":
        return !readOnly && [1001, 1003, 1005].includes(status);
      case "delete":
        return !readOnly && [1001, 1003, 1005].includes(status) && !isContractDocumentRelation;
      case "withdraw":
        return !readOnly && status === 1002;
      case "hold":
      case "finish":
      case "authorize":
      case "cancel":
        return (!readOnly || entry === "maintain") && status === 1004;
      case "change":
        return !readOnly && status === 1004 && contractChangeEnabled;
      case "mention":
        return status === 1004 || status === 1002;
      case "unHold":
        return (!readOnly || entry === "maintain") && status === 6001;
      case "back":
        return true;
    }
  };

  buttons = {
    edit: messages("common.edit") /*编辑*/,
    submit: messages("common.submit") /*提交*/,
    delete: messages("finance-6.key75") /*删除合同*/,
    withdraw: messages("common.withdraw") /*撤回*/,
    hold: messages("finance-6.key5") /*暂挂*/,
    finish: messages("finance-6.key7") /*已完成*/,
    change: messages("finance-6.key141") /*变更*/,
    unHold: messages("finance-6.key8") /*取消暂挂*/,
    cancel: messages("common.cancel") /*取消*/,
    back: messages("common.back") /*返回*/,
  };

  render() {
    const { entityOID, contractInfo, refreshContractInfo, customFormPropertyMap, detail } = this.props;
    const { loadingBtn, designateVisible, nodeList } = this.state;
    return (
      <Affix offsetBottom={0} className="bottom-bar">
        <Space>
          {[
            "edit",
            "submit",
            "delete",
            "withdraw",
            "hold",
            "finish",
            "authorize",
            "change",
            "mention",
            "cancel",
            "unHold",
            "back",
          ]
            .filter(this.filterButtons)
            .map((key) => {
              if (key === "edit")
                return (
                  <Button type="primary" onClick={this.handleEdit}>
                    {messages("common.edit") /*编辑*/}
                  </Button>
                );
              if (key === "authorize")
                return <AuthorizeBtn contractHeaderId={(((detail || {}).state || {}).headerData || {}).id} />;
              if (key === "mention")
                return (
                  <MentionBtn
                    ghost
                    info={contractInfo}
                    customFormPropertyMap={customFormPropertyMap}
                    goBack={refreshContractInfo}
                    entityType={6001}
                    entityOID={entityOID}
                  />
                );
              if (key === "back")
                return <Button onClick={() => this.handleBack()}>{messages("common.back") /*返回*/}</Button>;
              return (
                <Button
                  ghost={["cancel", "finish", "change"].includes(key)}
                  type={["cancel", "delete"].includes(key) ? "danger" : "primary"}
                  loading={loadingBtn === key}
                  onClick={this["handle" + key.replace(/^\w/, (target) => target.toUpperCase())]}
                >
                  {this.buttons[key]}
                </Button>
              );
            })}
        </Space>
        <Designate
          entity={{
            entityType: 6001,
            entityOID,
          }}
          modalVisible={designateVisible}
          nodeList={nodeList}
          onClose={this.handleCloseDesignate}
        />
      </Affix>
    );
  }
}

ContractBottomBar.contextTypes = {
  router: React.PropTypes.object,
};

export default ContractBottomBar;
